package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApArticleSearchService;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {

    @Autowired(required = false)
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1,检查参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //异步调用保存搜索记录
        ApUser user = AppThreadLocalUtil.getUser();
        //如果用户存在且在首页（加载多次无需保存）
        if(user != null && dto.getFromIndex() == 0){
            apUserSearchService.insert(dto.getSearchWords(), user.getId());
        }

        //2,条件查询
        // 1.1 准备Request(搜索请求对象，并指定索引库)
        SearchRequest request = new SearchRequest("app_info_article");
        // 1.2 创建所有的条件对象
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 2.1 创建布尔查询(封装多个query对象)
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //关键字索引(在title或content字段中查询)
        QueryStringQueryBuilder wordQuery = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title")
                .field("content").defaultOperator(Operator.OR);
        //必须匹配，参与算分
        boolQueryBuilder.must(wordQuery);

        //按发布时间排序
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime")
                .lt(dto.getMinBehotTime().getTime());
        //必须匹配，不参与算分
        boolQueryBuilder.filter(rangeQueryBuilder);

        //分页查询，倒叙排序
        sourceBuilder.from(0);
        sourceBuilder.size(dto.getPageSize());
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //结果高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //三要素：字段，前缀，后缀
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        // 加入高亮
        sourceBuilder.highlighter(highlightBuilder);

        // 2.2 将boolQueryBuilder放入sourceBuilder
        sourceBuilder.query(boolQueryBuilder);
        // 1.3 将请求对象条件放入请求
        request.source(sourceBuilder);
        // 1.4 client查询参数
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //3,结果封装
        ArrayList list = new ArrayList();
        SearchHit[] hits = response.getHits().getHits();
        //处理高亮
        for (SearchHit hit : hits) {
            //hit为json格式数据，转为map
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            if(hit.getHighlightFields() != null && hit.getHighlightFields().size() != 0){
                //getFragments为获取所有
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",title);
            }else{
                //原始标题
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
